package com.atguigu.spzx.manager.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.service.utils.AuthContextUtil;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.common.service.exception.GuiguException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private  SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    @Transactional(readOnly = true)
    public LoginVo selectUserByUsername(LoginDto loginDto) {
        String captcha = loginDto.getCaptcha();//用户输入的验证码
        String codeKey = loginDto.getCodeKey();//redis中验证码的数据key
        //验空
        if(StringUtils.isEmpty(captcha)||StringUtils.isEmpty(codeKey)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        String redisCode = redisTemplate.opsForValue().get("user:code:" + codeKey);
        //判断用户输入的验证码和从redis中获取的验证码是否一致
        if (!captcha.equalsIgnoreCase(redisCode)) {
            throw new GuiguException(ResultCodeEnum.CODE_ERROR);
        }
        redisTemplate.delete("user:code:"+codeKey);


        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();

        //判断账号密码是否为空
        if(StringUtils.isEmpty(userName)||StringUtils.isEmpty(password)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //获取用户对象
        SysUser sysUser = sysUserMapper.selectUserByUsername(userName);
        //判断用户是否存在
        if (sysUser == null) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_NOT_EXSIT);
        }
        //验证密码是否正确
        if (!sysUser.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }
        //判断账号是否被停用
        if (sysUser.getStatus().intValue()==0) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        //登录成功 使用UUID随机生成一个字符串作为token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        //以token为key将用户信息保存到Redis中，并设置有效时间为2小时
        //将SysUser对象转换为JSON字符串
        String s = JSONObject.toJSONString(sysUser);
        redisTemplate.opsForValue().set("user:login:"+token,s,2, TimeUnit.HOURS);


        return loginVo;
    }

   /* @Override
    public SysUser getSysUserInfo(String token) {
        String s = redisTemplate.opsForValue().get("user:login:" + token);//根据token获取redis里用户信息
        SysUser sysUser = JSONObject.parseObject(s, SysUser.class);//json解析对象
        return sysUser;
    }*/

    @Override
    public void logout(String token) {
       redisTemplate.delete("user:login:" + token);
    }

    /**
     * 分页带条件查询用户信息
     * @param current 当前页
     * @param size 页大小
     * @param sysUserDto 用户请求对象
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public PageInfo findByPage(Integer current, Integer size, SysUserDto sysUserDto) {
        PageHelper.startPage(current,size);
        List<SysUser> list=sysUserMapper.selectByPage(sysUserDto);
        PageInfo<SysUser> sysUserPageInfo = new PageInfo<>(list);
        return sysUserPageInfo;
    }

    @Override
    public void addUser(SysUser sysUser) {
        //加密
        String s = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(s);
        sysUserMapper.insertUser(sysUser);
    }

    @Override
    @Transactional(readOnly = true)
    public SysUser getById(Long id) {
      SysUser sysUser=sysUserMapper.getById(id);
        return sysUser;
    }

    @Override
    public void updateById(SysUser sysUser) {
        sysUserMapper.updateById(sysUser);
    }

    @Override
    public void deleteById(Long id) {
        sysUserMapper.deleteById(id);
    }


}
